package com.self.cloudmall.oms.interceptor;

import com.self.cloudmall.common.constant.SsoConstant;
import com.self.cloudmall.common.dto.LoginUserDto;
import com.self.cloudmall.common.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class ValidUserLoginInterceptor implements HandlerInterceptor {

    @Value("${unlogin.invoke.interface:}")
    private String excludeUri;

    //校验用户是否登录
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!StringUtils.isEmpty(excludeUri)){
            String[] split = excludeUri.split(",");
            String uri = request.getRequestURI();
            AntPathMatcher matcher = new AntPathMatcher();
            for (String s : split){
                if (!StringUtils.isEmpty(s) && matcher.match(s.trim(),uri)){
                    return true;
                }
            }
        }
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(SsoConstant.LOGIN_USER);
        if (attribute == null){
            session.setAttribute("validMsg","请先登录，再结算");
            response.sendRedirect("http://sso.cloudmall.com/login.html?originUrl=http://order.cloudmall.com"+request.getRequestURI());
            return false;
        }
        ThreadLocalUtil.set((LoginUserDto)attribute);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
